import csv
import re
from aip import AipNlp
import os


def Word_frequency():
    file_data = csv.reader(open('weibo_advertising_2.csv','r',encoding='utf8'))
    weibo_conetent_list = [item[10] for item in file_data]
    weibo_content = ','.join(weibo_conetent_list)
    

    with open("3评论语料库 - 广告.txt",'r',encoding='utf8') as f:
        word_text = f.read()
        word_text_list = re.findall( u"[\u4e00-\u9fa5]+",word_text)#词库的词通过正则全部匹配出来

        for word in word_text_list:
            with open(r'C:\Pythonfile\Funny\数据分析\result\advertising_2_weibo_comments_Word_frequency_result.csv','a',encoding='utf8',newline='') as f:
                writer = csv.writer(f)
                writer.writerow((word,weibo_content.count(word)))

            print('{}  出现的频率：{}'.format(word,weibo_content.count(word)))
            
def sentiment_Analysis():
    APP_ID = '11688814'
    API_KEY = '67rU3I4pXY9ch1k2mB1FMzfB'
    SECRET_KEY = 'IP4givnVwb3yyS7L2S66OXEmX3hC8E2b'
    
    client = AipNlp(APP_ID, API_KEY, SECRET_KEY)  # 自然语言处理，调用模块。
    reslut = csv.reader(open('sport_weixin_comment_2.csv', 'r', encoding='utf8'))
    for item in reslut:
        try:
            comment_text = item[10]
            sentiment_text = client.sentimentClassify(comment_text)
            positive_prob = sentiment_text.get("items")[0].get("positive_prob")  # 正面打分
            negative_prob = sentiment_text.get("items")[0].get("negative_prob")  # 负面打分
            sentiment = sentiment_text.get("items")[0].get("sentiment")  # 判断正负面情感
            with open(r'C:\Pythonfile\Funny\数据分析\result\sport_weibo_2_emotional_result.csv', 'a', encoding='utf8', newline='') as f:
                writer = csv.writer(f)
                writer.writerow((comment_text,positive_prob,negative_prob,sentiment))
            print(comment_text,positive_prob,negative_prob,sentiment)
        except Exception as e:
            print(e)



if __name__ == '__main__':
    sentiment_Analysis()